<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
//软删除
use Illuminate\Database\Eloquent\SoftDeletes;
use App\Models\Traits\Btn;

class Base extends Model
{
    //软删除
    use SoftDeletes,Btn;
    protected $dates=['deleted_at'];
    //设置添加时的黑名单
    protected $guarded=[];

    /**
     *
     * @param array $data 结果集 (整个表的结果)
     * @param int $fid 父类ID
     * @param array $result 结果数据
     * @param int $deep 分类级数
     * @return array
     */
//    public function getTree($list, $pid = 0, &$result = array(), $deep = 0)
//    {
//        $deep += 1;
//        foreach ($list as $k=>$v){   //遍历之后，此处的$k是键(其实是数组的序列号)，$v是一条数据结果
//            if($v->pid==$pid){
//                $result[$k]['id'] = $v->id;
//                $result[$k]['name'] = "|".str_repeat("-", $deep).$v->name;
//                $result[$k]['url'] = $v->url;
//                $result[$k]['pid'] = $v->pid;
//                $this->getTree($list, $v->id, $result, $deep);
//            }else{
//                continue;
//            }
//        }
//        return $result;
//    }
    /**
     * 数组的合并，并加上html标识前缀
     * @param array $data
     * @param int $pid
     * @param string $html
     * @param int $level
     * @return array
     */
    public function treeLevel(array $data, int $pid = 0, string $html = '--', int $level = 0) {
        static $arr = [];
        foreach ($data as $val) {
            if ($pid == $val['pid']) {
                // 重复一个字符多少次
                $val['html'] = str_repeat($html, $level * 2);
                $val['level'] = $level + 1;
                $arr[] = $val;
                $this->treeLevel($data, $val['id'], $html, $val['level']);
            }
        }
        return $arr;
    }

    public function subTree(array $data,int $pid=0)
    {
        $arr=[]; //返回的结果
        foreach ($data as $val)
        {
            //给定的PID是当前记录的上级ID
            if($pid==$val['pid']){
                //递归
                $val['sub'] = $this->subTree($data,$val['id']);
                $arr[] = $val;
            }
        }
        return $arr;
    }
}
